package org.spring.demo.service;

import org.spring.demo.domain.User;
import org.spring.demo.event.UserEvent;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author yangjian
 */
@Component
public class UserService implements ApplicationContextAware {

	private JdbcTemplate jdbcTemplate;
	private OrderService orderService;

	@Resource
	private UserService userService;
	private ApplicationContext applicationContext;

	// The parameter injection：
	// get Bean by type, if only find one, use it
	// if more than one, use bean name as filter
	public UserService(OrderService orderService, JdbcTemplate jdbcTemplate)
	{
		this.orderService = orderService;
		this.jdbcTemplate = jdbcTemplate;
	}

	public void test()
	{
		System.out.println("Hello UserService !");

		applicationContext.publishEvent(new UserEvent(new User("Rock", 18)));
	}

	@Transactional
	public void add()
	{
		jdbcTemplate.execute("insert user values(1, 'xiaoming')");
		// 通过 UserService 代理对象调用，事务生效。触发事务传播异常：
		// Existing transaction found for transaction marked with propagation 'never'
		userService.add1();
		// 如果这样直接调用，则是表示是 UserService 实例对象调用 add1()，此时事务是生效的。
		add1();
		throw new RuntimeException();
	}

	@Transactional(propagation = Propagation.NEVER)
	public void add1()
	{

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
	{
		this.applicationContext = applicationContext;
	}
}
